﻿(function () {
    function _clearFormat(str) {
        if (str == null || str == undefined) return "";
        var re = /<br.*?\/?>/gi;
        str = str.replace(re, "[br]");
        re = /<(.*)[^>]*>(.*)<\/\1>/gi;
        str = str.replace(re, function ($0, $1, $2) {
            if ($1.toLowerCase() == "img") { return $0; }
            if ($1.toLowerCase() == "strong") { return $2; }
            return "<" + $1 + ">" + $2 + "<" + $1 + "/>";
        });
        str = str.replace(/\[br\]/gi, "<br />");
        return str;
    }
    pluginName = "pastehandle";
    //Paste Handle
    CKEDITOR.plugins.add(pluginName,
	{
	    init: function (editor) {
	        editor.on("paste", function (evt) {
	            var html = evt.data.dataValue;
	            if (html) {
	                try {
	                    html = window.external.ClearHtmlStyle(html);
	                } catch (e) {
	                    html = _clearFormat(html);
	                }

	            }
	            evt.data.dataValue = html;
	        });
	        editor.on("contentDom", function () {
	            var container;
	            if (editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE) {
	                container = editor.container;
	            } else {
	                container = editor.document.getBody();
	            }
	            container.on('keyup', function (evt) {
	                if (!CKEDITOR.env.gecko && evt.data.getKeystroke() == CKEDITOR.CTRL + 86) {
	                    try {
	                        var imageUrl = window.external.GetClipboardImg();
	                        if (imageUrl != '') {
	                            var element = CKEDITOR.dom.element.createFromHtml('<img src="file:///' + imageUrl + '" />');
	                            evt.sender.editor.insertElement(element);
	                            evt.stop();
	                            evt.cancel();
	                        }
	                    } catch (e) { }
	                }
	            });
	        });
	    }
	});
})();
